package com.yowasa.xiuxian.service;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mysql.cj.xdevapi.JsonArray;
import com.yowasa.xiuxian.constant.MysApiPath;
import com.yowasa.xiuxian.constant.MysConfig;
import com.yowasa.xiuxian.entity.mys.SendMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
/**
 * mys接口请求工具
 **/
@Service
public class MysReplyServise {
//  id: 102040970
//  # 机器人令牌
//  token: m5xbTrZ70qMuGvdATZ3L3SnXjqNfGpT4
//  # api地址
//  api: https://bbs-api.miyoushe.com
    @Value("${mys.id}")
    private String botId;

    @Value("${mys.token}")
    private String botToken;

    @Value("${mys.pubKey}")
    private String pubKey;


    public static final Logger logger = LoggerFactory.getLogger(MysReplyServise.class);
    @Autowired
    private MysConfig config;

    public String basePost(String url,JSONObject jsonObject,String villaId){

        //x-rpc-bot_id	bot_id，平台下发的机器人唯一标志
        //x-rpc-bot_secret	bot_secret ，平台下发的机器人鉴权标志
        //x-rpc-bot_villa_id	villa_id，大别野 id
        logger.info("post-----------------------sendMessage,,,,,{}",jsonObject);
        logger.info("post-----------------------villaId,,,,,{}",villaId);
        String s = pubKey.replaceAll(" ", "\n");
        String key = "-----BEGIN PUBLIC KEY-----\n"+s+"\n-----END PUBLIC KEY-----\n";
        String sha256 = hmacSha256(key, botToken);
        String body = HttpUtil.createPost(url)
                .header("x-rpc-bot_id",botId)
                .header("x-rpc-bot_secret",sha256)
                .header("x-rpc-bot_villa_id",villaId)
                .contentType("application/json")
                .body(JSONUtil.toJsonStr(jsonObject)).execute().body();
        return body;
    }

    public String baseGet(String url,String villaId){

        //x-rpc-bot_id	bot_id，平台下发的机器人唯一标志
        //x-rpc-bot_secret	bot_secret ，平台下发的机器人鉴权标志
        //x-rpc-bot_villa_id	villa_id，大别野 id
        logger.info("post-----------------------villaId,,,,,{}",villaId);
        String s = pubKey.replaceAll(" ", "\n");
        String key = "-----BEGIN PUBLIC KEY-----\n"+s+"\n-----END PUBLIC KEY-----\n";
        String sha256 = hmacSha256(key, botToken);
        String body = HttpUtil.createGet(url)
                .header("x-rpc-bot_id",botId)
                .header("x-rpc-bot_secret",sha256)
                .header("x-rpc-bot_villa_id",villaId)
                .contentType("application/json")
                .execute().body();
        return body;
    }


    public static String hmacSha256(String pubKey, String botSecret) {
        try {
            SecretKeySpec signingKey = new SecretKeySpec(pubKey.getBytes("utf-8"), "HmacSHA256");
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(signingKey);
            byte[] rawHmac = mac.doFinal(botSecret.getBytes("utf-8"));
            return bytesToHex(rawHmac);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    private static String bytesToHex(byte[] bytes) {
        String hex = new BigInteger(1, bytes).toString(16);
        return hex;
    }
//    public static String bytesToHex(byte[] bytes) {
//        StringBuffer sb = new StringBuffer();
//        if (bytes != null && bytes.length > 0) {
//            for (int i = 0; i < bytes.length; i++) {
//                String hex = byteToHex(bytes[i]);
//                sb.append(hex);
//            }
//        }
//        return sb.toString();
//    }

    public String sendTextMessage(SendMessage message,String content) {
        String url = config.getUrl(MysApiPath.SEND_MESSAGE);
        JSONObject jsonObject =new JSONObject();
        jsonObject.put("room_id",message.getRoom_id());
        jsonObject.put("object_name","MHY:Text");

//                "room_id": 95333,
//                "object_name": "MHY:Text",
//                "msg_content": 序列化结构体

        // jsonObject put  msg_content

        //content	MsgContent	消息内容
        //mentionedInfo	MentionedInfo	消息的提及信息
        //quote	QuoteInfo	引用消息的信息
        JSONObject contentObject =new JSONObject();
        //content内容体
        // text String  entities  List
        // {                              entities 中的一个
        //        "entity": {
        //          "type": "mentioned_robot", // 提及机器人
        //          "bot_id": "bot_c85497cf3408304022" // 机器人 id
        //        },
        //        "length": 7,   结束位置
        //        "offset": 0    起始位置
        //  }
        contentObject.put("content",new JSONObject().put("text",content).put("entities",new JsonArray()));
        //消息中有提及艾特时需要
//        contentObject.put("mentionedInfo",null);
        //消息发送需要引用回复时需要
//        contentObject.put("quote",null);

        jsonObject.put("msg_content",JSONUtil.toJsonStr(contentObject));

        return basePost(url, jsonObject,message.getVilla_id());


    }

    public String sendPanelTextMessage(SendMessage message, String content, JSONObject componentObj) {
        String url = config.getUrl(MysApiPath.SEND_MESSAGE);
        JSONObject jsonObject =new JSONObject();
        jsonObject.put("room_id",message.getRoom_id());
        jsonObject.put("object_name","MHY:Text");

        JSONObject contentObject =new JSONObject();
        contentObject.put("content",new JSONObject().put("text",content).put("entities",new JsonArray()));
        contentObject.put("panel",componentObj);
        jsonObject.put("msg_content",JSONUtil.toJsonStr(contentObject));


        return basePost(url, jsonObject,message.getVilla_id());


    }


    public String sendImageMessage(SendMessage message,String url) {
        String sendUrl = config.getUrl(MysApiPath.SEND_MESSAGE);

        JSONObject jsonObject =new JSONObject();
        jsonObject.put("villa_id",message.getVilla_id());
        jsonObject.put("room_id",message.getRoom_id());
        jsonObject.put("object_name","MHY:Image");
        JSONObject contentObject =new JSONObject();
        JSONObject sizeObj = new JSONObject();
        sizeObj.put("height",16);
        sizeObj.put("width",9);
        contentObject.put("content",new JSONObject().put("url",url).put("size",sizeObj));

        jsonObject.put("msg_content",JSONUtil.toJsonStr(contentObject));

        return basePost(sendUrl, jsonObject,message.getVilla_id());


    }

    public String transferImage(SendMessage message,String url) {
        String sendUrl = config.getUrl(MysApiPath.TRANSFER_IMAGE);

        JSONObject jsonObject =new JSONObject();
        jsonObject.put("url",url);
        return basePost(sendUrl, jsonObject,message.getVilla_id());

    }

    public String getVillaInfo(SendMessage message){
        String sendUrl = config.getUrl(MysApiPath.GET_VILLA_INFO);
        return basePost(sendUrl, new JSONObject(),message.getVilla_id());
    }

    public String getMemberRoles(SendMessage message) {
        String sendUrl = config.getUrl(MysApiPath.GET_MEMBER_ROLE_LIST);
        return baseGet(sendUrl,message.getVilla_id());
    }

    public String operateMemberToRole(SendMessage message, JSONObject object) {
        String sendUrl = config.getUrl(MysApiPath.UPDATE_USER_TO_MEMBER_ROLE);
        return basePost(sendUrl, object, message.getVilla_id());
    }

    public String removeMember(SendMessage message, long uid) {
        String sendUrl = config.getUrl(MysApiPath.DELETE_VILLA_MEMBER);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uid",uid);
        return basePost(sendUrl, jsonObject, message.getVilla_id());
    }
}
